package net.gz01.wallet.web.controller.api;

import static net.gz01.wallet.web.config.FDDConfig.APP_ID;
import static net.gz01.wallet.web.config.FDDConfig.APP_SECRET;
import static net.gz01.wallet.web.config.FDDConfig.HOST;
import static net.gz01.wallet.web.config.FDDConfig.V;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.LinkedHashMap;

import com.alibaba.fastjson.JSON;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.ApplyCert;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;

import lombok.extern.slf4j.Slf4j;
import net.gz01.util.ZODate;
import net.gz01.util.ZOString;
import net.gz01.wallet.channel.fadada.FadadaChannel;
import net.gz01.wallet.message.QueryReq;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.config.SystemEnum;
import net.gz01.wallet.web.model.Merch;
import net.gz01.wallet.web.model.base.FddOrder;

/**
 * 代付通知控制器
 *
 * @author Reed
 *
 */
@Slf4j
@Clear
public class NotifyController extends Controller {
	private static final String SAFE_KEY = SystemConfig.channelConfig.get("etransfar_safeKey");// 密钥
	private static final String YYT_KEY = SystemConfig.channelConfig.get("yyt_key");// 密钥



	//实名认证异步回调
	public void fdd_verify(){
		String parameterString = "";
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(getRequest().getInputStream(), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String string;
			while ((string = reader.readLine()) != null) {
				buffer.append(string);
			}
			parameterString = URLDecoder.decode(buffer.toString(), "UTF-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("实名认证异步--->收到FDD异步通知-> \r\n" + parameterString);

		//"appId=401849&customerId=DCFD9D437F48ED0EDB553424F80CD4C6&status=2&serialNo=93b03fc9e88d4219821e1628dea115bc&statusDesc="

		LinkedHashMap<String, String> resMap = ZOString.convertUrlParameterToMap(parameterString);
		String appId = resMap.get("appId");
		String customerId=resMap.get("customerId");
		String status = resMap.get("status");
		String serialNo=resMap.get("serialNo");
		if(!APP_ID.equals(appId)){
			log.info("实名认证异步--->ERROR->" + "appid不一致");
			renderHtml("error");
			return;
		}

        FddOrder order = FddOrder.dao.selectByOrder(false, customerId, serialNo);
		if(order!=null && order.getUserCode()!=null && order.getType()!=null){
            Merch user = Merch.dao.selectByMerchCode(order.getUserCode());
			if("1".equals(order.getType())){//个人实名认证的
				if("2".equals(status)){
					ApplyCert applyCert = new ApplyCert(APP_ID,APP_SECRET,V,HOST);
					String customer_id = order.getCustomerId();
					String verified_serialno= order.getFddOrderNo();
					String result = applyCert.invokeApplyCert(customer_id,verified_serialno);
					log.info("FDD-->个人实名认证的正式申请返回:" + result);//FDD-->实名认证的正式申请返回:{"code":1,"msg":"success"}
					if("1".equals(JSON.parseObject(result).getString("code"))) {
						order.setResCode(SystemEnum.Resp.Success.getCode());
                        order.setFinishTime(ZODate.getDateTime());
                        order.update();

                        user.setIsVerify(true);
                        user.setCustomerId(order.getCustomerId());
                        user.setTransactionNo(order.getFddOrderNo());
						user.update();
					}
				}
			}
			if("2".equals(order.getType())){//企业实名认证的
				if("4".equals(status)){
					ApplyCert applyCert = new ApplyCert(APP_ID,APP_SECRET,V,HOST);
					String customer_id = order.getCustomerId();
					String verified_serialno= order.getFddOrderNo();
					String result = applyCert.invokeApplyCert(customer_id,verified_serialno);
					log.info("FDD-->企业实名认证的正式申请返回:" + result);//FDD-->实名认证的正式申请返回:{"code":1,"msg":"success"}

					if("1".equals((JSON.parseObject(result)).getString("code"))) {
						order.setResCode(SystemEnum.Resp.Success.getCode());
						order.setFinishTime(ZODate.getDateTime());
                        order.update();
                        user.setIsVerify(true);
                        user.setCustomerId(order.getCustomerId());
                        user.setTransactionNo(order.getFddOrderNo());
                        user.update();
					}
				}
			}
			new FadadaChannel().queryFadada(new QueryReq(), order, user);

		}

		renderHtml(parameterString);
	}
	//签署合同的异步回调
	public void fdd_sign(){
		String parameterString = "";
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(getRequest().getInputStream(), "UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String string;
			while ((string = reader.readLine()) != null) {
				buffer.append(string);
			}
			parameterString = URLDecoder.decode(buffer.toString(), "UTF-8");

		} catch (Exception e) {
			e.printStackTrace();
		}
		/*
		transaction_id=T822603F951220932813299713&contract_id=H249912F951220932813299712&timestamp=20190506122833&result_code=3000&result_desc=签章成功&msg_digest=NDFBNzdEQjEyOTYxQTk4MEY3Q0E3MjA2MDAyOTJBMzBDMUMzNkUzQw==&download_url=https://testapi.fadada.com:8443/api//getdocs.action?app_id=401849&timestamp=20190506122755&v=2.0&msg_digest=M0QzREM1NkRCMDk4QTZFRjcxRTIzMTBFODY4RkJDMjJGOUUwQ0FDQw==&send_app_id=null&transaction_id=T822603F951220932813299713&viewpdf_url=https://testapi.fadada.com:8443/api//viewdocs.action?app_id=401849&timestamp=20190506122755&v=2.0&msg_digest=M0QzREM1NkRCMDk4QTZFRjcxRTIzMTBFODY4RkJDMjJGOUUwQ0FDQw==&send_app_id=null&transaction_id=T822603F951220932813299713
		 */
		log.info("合同签署异步--->收到FDD异步通知-> \r\n" + parameterString);

		renderHtml(parameterString);
	}
}
